<?php

namespace App\Models\Home;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Knowledge extends Model
{
    protected $table = 'knowledge';
    protected $guarded = [];

    public function user()
    {
        return $this->belongsTo('App\Models\Home\Users','assign','id');
    }

    public function file()
    {
        return $this->belongsTo('App\Models\Home\File','attachment','id');
    }

    public function getList($between=array(),$skip=0,$limit,$opt=array()){
        $query = self::orderBy('id','desc')->with(['user']);

        if ($between && count($between) == 2){
            $query = $query->whereBetween('updated_at', $between);
        }

        if (!empty($opt)){
            foreach ($opt as $k => $v){
                if(is_array($v) && $v[1]){
                    $query = $query->where($k,$v[0],$v[1]);
                }elseif(!is_array($v) && $v !== false){
                    $query = $query->where($k,$v);
                }
            }
        }

        if (isset($limit)){
            $query = $query->skip($skip)->limit($limit);
        }

        $list = $query->get();

        foreach ($list as $k => $v){

            $list[$k]->user_name = $v->user?$v->user->username:'';

            switch ($v->category){
                case 1;
                    $list[$k]->category_name = '候选人回访';
                    break;
                case 2;
                    $list[$k]->category_name = '客户资料';
                    break;
                case 3;
                    $list[$k]->category_name = '顾问分享';
                    break;
                case 4;
                    $list[$k]->category_name = '入职培训';
                    break;
                case 5;
                    $list[$k]->category_name = '技能培训';
                    break;
                case 6;
                    $list[$k]->category_name = '经验分享';
                    break;
                default:
                    $list[$k]->category_name = '公司制度';
            }

        }

        return $list;

    }

    public function getCount($between=array(), $opt=array()){
        $query = self::orderBy('id','desc');

        if (!empty($between)){
            $query = $query->whereBetween('updated_at', $between);
        }

        if (!empty($opt)){
            foreach ($opt as $k => $v){
                if(is_array($v) && $v[1]){
                    $query = $query->where($k,$v[0],$v[1]);
                }elseif(!is_array($v) && $v !== false){
                    $query = $query->where($k,$v);
                }
            }
        }

        $count = $query->count();

        return $count;
    }


}
